import Taro, { Component } from "@tarojs/taro";
import { connect } from "@tarojs/redux";
import { View, Text, Swiper, SwiperItem, RichText } from "@tarojs/components";
import { AtButton, AtTag, AtFloatLayout, AtInputNumber } from "taro-ui";
import BaseComponent from "@components/BaseComponent";
import { $Req } from "@utils";
import "./index.scss";
import "@components/ShowBox.scss";

@connect(
  ({ userModel, orderModel }) => ({
    userModel,
    orderModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
    orderAction: dispatch.orderModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "商品详情",
  };

  constructor() {
    super(...arguments);
    const { goodsId } = this.$router.params;
    this.state = {
      // 商品id
      goodsId,
      cartStatus: false,
      showDetail: false,
      goodsDetail: {},
      goodsAttr: {
        goodsattrName: null,
        goodsattrvalue: [],
      },
      skuCurrent: {},
      skuIndex: 0,
      ggList: []
    };
  }


  initImgSwiper() {
    const { goodsDetail } = this.state;
    return (
      <View className="at-row swiper-detail">
        <View className="at-col">
          <Swiper
            indicatorColor="#ccc"
            indicatorActiveColor="#fff"
            circular
            indicatorDots
            autoplay
          >
            {goodsDetail.skuImgUrl.map((item, index) => {
              return (
                <SwiperItem key={index}>
                  <View className="at-row swiper-item">
                    <View className="at-col">
                      <Image mode={"aspectFill"} src={item} />
                    </View>
                  </View>
                </SwiperItem>
              );
            })}
          </Swiper>
        </View>
      </View>
    );
  }
  componentDidMount() {
    const { orderAction } = this.props;

    orderAction.setStatus({
      goodsCount: 1,
    });
  }
  componentDidShow() {
    this.getGoodsDetail();
    const { orderAction } = this.props;

    orderAction.setStatus({
      skuId: 0,
    });

    let shareId = this.$router.params.userId;
    console.log("获取到分享人的id：", shareId);

    if (shareId) {
      Taro.setStorageSync("shareId", shareId);
    }

  }

  async getGoodsDetail() {
    Taro.showLoading({
      title: "加载中..."
    })
    let { code, message, data } = await $Req({
      type: "get",
      url: "/goods/getGoodsDetail",
      data: {
        skuId: this.state.goodsId
      },
    });

    if (code != 200) {
      Taro.hideLoading();
      return false;
    } 

    Taro.hideLoading();

    data.skuImgUrl = data.skuImgUrl.split(",");
    if (data.skuDetail) {
      data.skuDetail = data.skuDetail.replace(/\<img/gi, '<img style="width:100% !important;height:auto;display:block;"')
    }

    data.skuList.map((item, index) => {
      item.spuNo = data.spuNo;
      item.goodsName = data.goodsName;
      item.categoryId = data.categoryId;
      item.categoryName = data.categoryName;
      item.vip = data.vip;
      item.special = data.special;
      item.spuImgUrl = data.spuImgUrl;
      item.skuDetailImgUrl = data.skuDetailImgUrl;
      if (data.id == item.id) {
        this.setState({
          skuCurrent: item,
          skuIndex: index
        })
      }
    })
    this.setState({
      goodsDetail: data,
    }, () => {
      console.log(this.state.goodsDetail)
    });
    this.props.orderAction.setStatus({
      goodsDetail: data,
    });
  }

  onSubmitBtn() {

    const {
      userModel: { userInfo },
      userAction,
    } = this.props;

    // 整完加上
    if (!userInfo.userId) {
      userAction.setStatus({
        isOpen: true,
      });
      return;
    }

    let { cartStatus, goodsDetail, skuCurrent } = this.state;
    const { orderModel: { goodsCount, skuId } } = this.props;
    if (!skuId) {
      Taro.showToast({
        title: "请选择规格在提交",
        icon: "none"
      })

      return false;
    }

    // 购物车
    if (cartStatus) {
      this.addCart();
    }
    // 直接购买的 
    else {
      //delete goodsDetail.skuDetail
      skuCurrent[0].quantity = goodsCount;
      Taro.navigateTo({
        url: `/pages/order/confirm/index?orderList=${JSON.stringify(skuCurrent)}&totalMoney=${skuCurrent[0].skuCurrPrice * goodsCount}&totalProduct=${goodsCount}`,
      });
    }

  }

  onShareAppMessage(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    const {
      userModel: { userInfo },
    } = this.props;
    console.log(userInfo.userId)
    return {
      title: "晶品城好物特价：" + this.state.goodsDetail.goodsName,
      path: `/pages/mall/detail/index?goodsId=${this.state.goodsId}&userId=${userInfo.userId}`
    }
  }

  async addCart() {

    const {
      userModel: { userInfo },
      userAction,
    } = this.props;

    // 整完加上
    if (!userInfo.userId) {
      userAction.setStatus({
        isOpen: true,
      });
      return;
    }

    const { orderModel: { goodsCount, goodsDetail: { goodsSpuId, skuNo } } } = this.props;
    let { skuCurrent } = this.state;
    console.log(skuCurrent, "-------skuCurrent-----------")

    let { code, message, data } = await $Req({
      type: "POST",
      url: "/order/addCart",
      data: {
        skuNo: skuCurrent[0].skuNo,
        skuId: skuCurrent[0].id,
        quantity: goodsCount,
        userId: userInfo.userId
      },
    });
    if (!data) return;

    this.setState({
      showDetail: false
    })

    Taro.showToast({
      title: "加入购物车成功!"
    })
  }

  initDetailBox() {
    const { goodsDetail, skuIndex, ggList } = this.state;
    const { skuList } = goodsDetail;
    const {
      orderModel: { goodsCount, skuId },
      orderAction,
    } = this.props;

    return (
      <View className="at-row shopping-show-box">
        <View className="at-col show-box-c0">
          <View className="at-row show-box-row">
            <View className="at-col at-col-4 show-box-col-img">
              <image
                mode={"aspectFill"}
                className="img-goods"
                style="width:100PX;height:100PX;"
                src={skuList[skuIndex].skuCoversUrl}
              />
            </View>
            <View className="at-col at-col-8 show-box-col-main">
              <View className="at-row">
                <View className="at-col">
                  <Text className="show-box-title">
                    {skuList[skuIndex].goodsName}
                  </Text>
                </View>
              </View>
              <View className="at-row" style="margin-top:5PX;">
                <View className="at-col">
                  <Text className="show-box-price-large">
                    ￥{skuList[skuIndex].skuCurrPrice}
                  </Text>
                  <Text className="show-box-price-small">{skuList[skuIndex].skuCurrPrice >= 1 ? ".0元" : '元'}{goodsDetail.vip * 1 == 1 ? '' : '/积分'}</Text>
                  <Text className="show-box-price-discount" style={{ color: "#ccc", textDecoration: "line-through", fontSize: "12px", marginLeft: "10px" }}>
                    ￥{skuList[skuIndex].skuCostPrice}
                  </Text>
                </View>
              </View>
              <View className="at-row" style="margin-top:5PX;">
                <View className="at-col">
                  <Text className="show-box-norms">
                    编号:{skuList[skuIndex].skuNo}
                  </Text>
                </View>
              </View>
            </View>
          </View>
          <View className="at-row" style="margin-top:10PX;">
            <View className="at-col">
              <Text>{skuList[skuIndex].skuTitleType}</Text>
            </View>
          </View>
          <View className="at-row" style="flex-wrap: wrap;justify-content: flex-start; margin-top:10px">
            {
              goodsDetail.specsTypeList && goodsDetail.specsTypeList.map((el, i) => (
                <View>
                  <View className="at-row r3">
                    <View className="at-col">
                      <Text>{el.skuType}</Text>
                    </View>
                  </View>
                  {/* 规格 */}
                  <View className="at-row r4 size-wrap" style="padding:0 15PX;width:auto;background-color:#fff; flex-wrap: wrap; justify-content: flex-start;">
                    {el.specsList.map((item, index) => {
                      this.state.ggList = []
                      return (
                        <View
                          className="size-item"
                          key={item.id}
                          onClick={() => {
                            goodsDetail.specsTypeList[i].specsList.forEach(t => t.selected = false);
                            item.selected = true

                            ggList[i] = item.skuTitle;
                            this.setState({
                              ggList
                            })

                            let sssss = ggList.join("-");

                            if (ggList.length >= goodsDetail.specsTypeList.length) {
                              
                              let curr = skuList.filter((s, f) => {
                                s.integralStatus = goodsDetail.integralStatus;
                                return s.skuTitle == sssss;
                              });
  
                              let indexT = skuList.findIndex((s, f) => {
                                s.integralStatus = goodsDetail.integralStatus;
                                return s.skuTitle == sssss;
                              });

                              console.log(indexT);
                              this.setState({
                                skuCurrent: curr,
                                skuIndex: indexT,
                              })
                            }


                            orderAction.setStatus({
                              skuId: item.id,
                            });

                          }}
                        >
                          <AtTag
                            active={item.selected}
                            circle
                          >
                            {item.skuTitle}
                          </AtTag>
                        </View>
                      );
                    })}
                  </View>
                </View>
              ))

            }
          </View>
          <View
            className="at-row at-row__align--center"
            style="margin-top:10PX;"
          >
            <View className="at-col at-col-6" style="text-align:left;">
              数量
            </View>
            <View
              className="at-col at-col-6"
              style="text-align:right; margin-top:10PX;"
            >
              <AtInputNumber
                disabledInput
                min={1}
                max={100}
                step={1}
                value={goodsCount}
                onChange={(v) => {
                  orderAction.setStatus({
                    goodsCount: v,
                  });
                }}
              />
            </View>
          </View>
          <View className="at-row" style="margin-top:20PX;">
            <View className="at-col">
              <AtButton
                circle
                type="primary"
                onClick={() => this.onSubmitBtn()}
              >
                确定
              </AtButton>
            </View>
          </View>
        </View>
      </View>
    );
  }

  render() {
    const { goodsDetail, skuIndex, skuCurrent, ggList } = this.state;
    const { skuList } = goodsDetail;
    const {
      orderModel: { goodsCount, skuId },
      orderAction,
    } = this.props;
    return (
      <BaseComponent>
        <View className="page-goods-detail shopping-show-box">
          {this.initImgSwiper()}
          <View className="at-row r1">
            <View className="at-col at-col-9">
              <Text className="show-box-price-large">
                ￥{skuList[skuIndex].skuCurrPrice}
              </Text>
              <Text className="show-box-price-small">{skuList[skuIndex].skuCurrPrice >= 1 ? ".0元" : '元'}{goodsDetail.vip * 1 == 1 ? '' : '/积分'}</Text>
              <Text style={{ color: "#ccc", textDecoration: "line-through", fontSize: "12px", marginLeft: "10px" }}>￥{skuList[skuIndex].skuCostPrice}</Text>
            </View>
            <View className="at-col at-col-3" style="text-align: right;">
              <Text className="t1">销量{skuList[skuIndex].skuSaleNum}</Text>
            </View>
          </View>
          <View className="at-row at-row__justify--between at-row__align--center r2">
            <View className="shop-info">
              <View className="t1">优惠</View>
              <View className="t2">
                {skuList[skuIndex].goodsName}
              </View>
            </View>
            <View className="at-col at-col-3">
              <AtButton
                circle
                type="primary"
                className="btn-share"
                openType="share"
              >
                分享
              </AtButton>
            </View>
          </View>
          {/* <View className="at-row r3">
            <View className="at-col">
              <Text>{skuList[skuIndex].skuTitleType}</Text>
            </View>
          </View>
          <View className="at-row r4 size-wrap" style="padding:0 15PX;width:auto;background-color:#fff; flex-wrap: wrap; justify-content: flex-start;">
            {goodsDetail.skuList && goodsDetail.skuList.map((item,index) => {
              return (
                <View
                  className="size-item"
                  key={item.id}
                  onClick={() => {
                    this.setState({
                      skuIndex:index,
                      skuCurrent:item
                    })
                    orderAction.setStatus({
                      skuId: item.id,
                    });
                  }}
                >
                  <AtTag
                    active={skuId === item.id}
                    circle
                  >
                    {item.skuTitle}
                  </AtTag>
                </View>
              );
            })}
          </View> */}
          {
            goodsDetail.specsTypeList && goodsDetail.specsTypeList.map((el, i) => (
              <View>
                <View className="at-row r3">
                  <View className="at-col">
                    <Text>{el.skuType}</Text>
                  </View>
                </View>
                {/* 规格 */}
                <View className="at-row r4 size-wrap" style="padding:0 15PX;width:auto;background-color:#fff; flex-wrap: wrap; justify-content: flex-start;">
                  {el.specsList.map((item, index) => {
                    this.state.ggList = []
                    return (
                      <View
                        className="size-item"
                        key={item.id}
                        onClick={() => {
                          goodsDetail.specsTypeList[i].specsList.forEach(t => t.selected = false);
                          item.selected = true

                          ggList[i] = item.skuTitle;
                          this.setState({
                            ggList
                          })

                          let sssss = ggList.join("-");

                          if (ggList.length >= goodsDetail.specsTypeList.length) {
                            let curr = skuList.filter((s, f) => {
                              s.integralStatus = goodsDetail.integralStatus;
                              return s.skuTitle == sssss;
                            });

                            let indexT = skuList.findIndex((s, f) => {
                              s.integralStatus = goodsDetail.integralStatus;
                              return s.skuTitle == sssss;
                            });

                            this.setState({
                              skuCurrent: curr,
                              skuIndex: indexT,
                            })
                          }


                          orderAction.setStatus({
                            skuId: item.id,
                          });

                        }}
                      >
                        <AtTag
                          active={item.selected}
                          circle
                        >
                          {item.skuTitle}
                        </AtTag>
                      </View>
                    );
                  })}
                </View>
              </View>
            ))
          }

          {/* 详情 */}
          <View className="at-row r5">
            <View className="at-col">
              <AtButton
                onClick={() => {
                  // this.setState({
                  //   showDetail: true,
                  // });
                }}
              >
                详情
              </AtButton>
            </View>
          </View>
          {/* 详情 */}
          <RichText className='text' nodes={goodsDetail.skuDetail} />

          {/* 底部tabBar */}
          <View className="at-row bottom-row">
            <View className="at-col at-col-all">
              <View className="at-row at-row__justify--between at-row__align--center">
                <View className="at-col at-col-4" style="position: relative;">
                  <View className="at-row">
                    <View className="at-col">
                      <Image src={"https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" + "/shopping/mall/services.png"} />
                    </View>
                  </View>
                  <View className="at-row">
                    <View className="at-col">
                      <Text className="service">客服</Text>
                    </View>
                  </View>
                  <AtButton
                    className="btn-concat"
                    openType="contact"
                  ></AtButton>
                </View>
                <View className="at-col at-col-4">
                  <AtButton
                    circle
                    className="btn-submit btn-color"
                    onClick={() => {
                      const {
                        orderModel: { skuId },
                      } = this.props;

                      this.setState({
                        cartStatus: true
                      })

                      if (!skuId) {
                        this.setState({
                          showDetail: true
                        })
                        return false;
                      }

                      this.addCart();

                    }}
                  >
                    加入购物
                  </AtButton>
                </View>
                <View className="at-col at-col-4">
                  <AtButton
                    circle
                    type="primary"
                    className="btn-submit"
                    onClick={() => {
                      const {
                        userModel: { userInfo },
                        userAction,
                      } = this.props;

                      // 整完加上
                      if (!userInfo.userId) {
                        userAction.setStatus({
                          isOpen: true,
                        });
                        return;
                      }

                      const {
                        orderModel: { skuId },
                      } = this.props;

                      this.setState({
                        cartStatus: false
                      })

                      if (!skuId) {
                        this.setState({
                          showDetail: true
                        })
                        return false;
                      }

                      //delete goodsDetail.skuDetail
                      skuCurrent[0].quantity = goodsCount;
                      Taro.navigateTo({
                        url: `/pages/order/confirm/index?orderList=${JSON.stringify(skuCurrent)}&totalMoney=${skuCurrent[0].skuCurrPrice * goodsCount}&totalProduct=${goodsCount}&ggName=${ggList}`,
                      });
                    }}
                  >
                    立即购买
                  </AtButton>
                </View>
              </View>
            </View>
          </View>
          <AtFloatLayout
            isOpened={this.state.showDetail}
            onClose={() => {
              this.setState({
                showDetail: false,
              });
            }}
          >
            {this.initDetailBox()}
          </AtFloatLayout>
        </View>
      </BaseComponent>
    );
  }
}
